package org.flynenu.core.dao.base;

import java.util.Collections;
import java.util.List;

import org.flynenu.core.dao.CommonDAO;
import org.flynenu.core.entity.BaseEntity;
import org.hibernate.Query;
import org.hibernate.criterion.Example;

public class DefaultCommontDao extends BaseDao implements CommonDAO {
	public void save(BaseEntity entity) {
		try {
			session().save(entity);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void delete(BaseEntity entity) {
		try {
			session().delete(entity);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public <T extends BaseEntity> T queryById(Integer id, Class cls) {
		try {
			T instance = (T) session().get(cls, id);
			return instance;
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public <T extends BaseEntity> List<T> queryByExample(T example, Class cls) {
		try {
			
			List<T> results = session().createCriteria(generateDao(cls.getSimpleName())).add(Example.create(example)).list();
			return results;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public <T extends BaseEntity> List<T> queryByProperty(String filed, Object value) {
		try {
			StringBuilder sql = new StringBuilder().append("from Usertable as tab where tab.").append(filed).append("=?");
			Query queryObject = session().createQuery(sql.toString());
			queryObject.setParameter(0, value);
			
			List<T> list = (List<T>)queryObject.list();
			return (List<T>) (list == null? Collections.emptyList(): list);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void beginTransaction() {
		session().beginTransaction();
	}

	public void commitTransaction() {
		session().getTransaction().commit();
	}

	public void closeSession(){
		session().close();
	}
	
	private String generateDao(String value) {
//		return "dao." + value;
		return value;
	}
}
